﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FlexminAPI;
using FlexLib.Plugins;

namespace FlexminAdmin.Forms
{
	public partial class PluginsForm : Form
	{
		public PluginsForm()
		{
			InitializeComponent();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			LoadPluginsList();			
		}

		private void LoadPluginsList()
		{
			pluginsView.Items.Clear();

			IEnumerable<PluginInfo> plugins = PluginManager.AdminInstance.InstalledPlugins;

			foreach (PluginInfo plugin in plugins)
			{
				ListViewItem item = pluginsView.Items.Add(plugin.DisplayName);
				item.SubItems.Add(plugin.PluginVersion.ToString());
				item.SubItems.Add(plugin.Description);
				item.Tag = plugin.Name;
			}
		}

		private void installButton_Click(object sender, EventArgs e)
		{
			if (openPackageDialog.ShowDialog() != DialogResult.OK)
				return;

			try
			{
				PluginManager.AdminInstance.Install(openPackageDialog.FileName);
			}
			catch (PluginException ex)
			{
				MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			catch (PluginAlreadyInstalledException)
			{
				if (MessageBox.Show("Plugin already installed. Update it?", "Update", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
					return;

				try
				{
					PluginManager.AdminInstance.Upgrade(openPackageDialog.FileName);
				}
				catch (PluginException ex)
				{
					MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}
			}

			LoadPluginsList();
		}

		private void uninstallButton_Click(object sender, EventArgs e)
		{
			if (pluginsView.SelectedItems.Count == 0)
				return;

			ListViewItem selectedItem = pluginsView.SelectedItems[0];
			string pluginName = selectedItem.Tag as string;

			if (pluginName == null)
				return;

			if (MessageBox.Show("Uninstall this plugin?", "Uninstall", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
				return;

			try
			{
				PluginManager.AdminInstance.Uninstall(pluginName);
			}
			catch (PluginException ex)
			{
				MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			LoadPluginsList();
		}
	}
}
